import React, { useState, useEffect } from 'react';
import { useNavigate, Routes, Route, useLocation, Navigate } from 'react-router-dom';
import { Button, Layout, Card, notification, Modal, message, Avatar, Menu, Drawer, Row, Col, ConfigProvider } from 'antd';
const { confirm } = Modal;
import { Outlet, history } from 'umi';
import request from '@/utils/request'
import styles from './BasicLayout.less';
import PublicUtils from "@/utils/publicUtils";
import {
  MenuUnfoldOutlined,
  DashboardOutlined,
  TeamOutlined,
  UserOutlined
} from '@ant-design/icons';

const BasicLayout = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [open, setopen] = useState(false);
  const [userInfo, setUserInfo] = useState(JSON.parse(localStorage.getItem('userInfo')));
  const [title, setTitle] = useState("首页");
  const [path, setPath] = useState(location.pathname);
  const handleNavigate = () => {
    if (!userInfo) {
      navigate('/login');
    }
  };

  // 用于存储菜单权限信息的状态
  const [menuPermissions, setMenuPermissions] = useState([]);
  const [buttunVisiable, setButtunVisiable] = useState(false);

  useEffect(() => {
    const cachedPermissions = JSON.parse(localStorage.getItem('authorized'));
    if (cachedPermissions) {
      setMenuPermissions(cachedPermissions);
    }

    handleNavigate();
    setPath(location.pathname);
    const routerItem = items.find((item) => item.key === path);
    if (routerItem?.label) {
      setTitle(routerItem.label);
    }

    // 更新菜单的选中状态
    const menuItems = document.querySelectorAll('.ant-menu-item');
    menuItems.forEach(item => {
      item.classList.remove('ant-menu-item-selected');
    });
  
    const selectedMenuItem = document.querySelector(`.ant-menu-item[aria-label="${routerItem?.label}"]`);
    if (selectedMenuItem) {
      selectedMenuItem.classList.add('ant-menu-item-selected');
    }

    // 更新按钮显示状态的逻辑
    if (path === '/recruit/interviewResultMobile') {
      setButtunVisiable(true);
    } else {
      setButtunVisiable(false);
    }
  }, [userInfo, path,location.pathname]);


  const items = [
    {
      key: '/dashboard',
      icon: <DashboardOutlined style={{ fontSize: '20px' }} />,
      label: '首页'
    }, {
      key: '/business/deliveryPlan',
      icon: <TeamOutlined style={{ fontSize: '20px' }} />,
      label: '交付计划',
    }, {
      key: '/recruit/interviewResultMobile',
      icon: <TeamOutlined style={{ fontSize: '20px' }} />,
      label: '面试结果',
    }, {
      key: '',
      icon: <TeamOutlined style={{ fontSize: '20px' }} />,
      label: '退出登录',
    }
  ];


  //展开权限数据函数
  const flattenTree = (tree) => {
    let flattenedArray = [];
    const traverseTree = (node) => {
      flattenedArray.push(node);
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          traverseTree(child);
        });
      }
    };
    tree.forEach(node => {
      traverseTree(node);
    });
    return flattenedArray;
  };

  // 根据权限过滤后的菜单数组
  const filteredItems = items.filter((item) => {
    if (item.key === '') {
      // 特殊处理退出登录选项，始终显示
      return true;
    }
    const flattenedData = flattenTree(menuPermissions);
    // 假设权限信息是以包含菜单路径的对象数组形式存储，且对象有一个名为 'status' 的属性表示权限状态
    const permission = flattenedData.find((perm) => perm.path === item.key);
    return permission && permission.status;
  });

  const handleMenuClick = ({ item, key, keyPath, domEvent }) => {
    const routerItem = items.find((item) => item.key === key);
    if (routerItem) {
      setTitle(routerItem.label);

      // 更新按钮显示状态的逻辑
      if (key === '/recruit/interviewResultMobile') {
        setButtunVisiable(true);
      } else {
        setButtunVisiable(false);
      }

      if (key === '') {
        confirm({
          title: '退出系统确认',
          content: '确定要退出登录吗？',
          okText: '确定',
          cancelText: '取消',
          centered: true,
          async onOk() {
            request.get('/sysMain/logout', { type: 0 }).then(res => {
              if (res && res.error_code === 200) {
                window.localStorage.removeItem('x-token');
                window.localStorage.removeItem('userInfo');
                window.localStorage.removeItem('authorized');
                history.push('/login');

              } else {
                notification.error({
                  message: res ? res.error_msg : '请求错误'
                })
              }
            })
          }
        });
      } else {
        // 再次检查点击菜单的权限
        const flattenedData = flattenTree(menuPermissions);
        const permission = flattenedData.find((perm) => perm.path === key);
        if (permission && permission.status) {
          navigate(key);
        } else {
          notification.error({
            message: '您没有访问此页面的权限。'
          });
        }
      }
    }
  };

  const onOpen = () => {
    setopen(!open);
  };

  const onClose = () => {
    setopen(!open);
  }

  // 新增反馈面试结果
  const resultAdd = () => {
    history.push('/recruit/interviewfeedbackMobile');
  }

  return (
    <div className={styles.Layout}>
      <div className={styles.headerTitle}>
        <Row style={{ width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center' }}>
          <Col style={{ marginLeft: '20px' }}>
            <MenuUnfoldOutlined onClick={onOpen} style={{ fontSize: '20px', color: '#409EFF' }} />
          </Col>
          <Col offset={20} style={{ marginLeft: '25px', flexGrow: 1 }}>
            <div style={{ fontSize: '18px', color: '#333333' }}>{title}</div>
          </Col>
          <Col style={{ marginRight: '25px' }}>
            {PublicUtils.checkAuth('2020597_PERMS') &&buttunVisiable && <Button onClick={resultAdd} style={{ backgroundColor: '#409EFF', color: '#fff', borderRadius: '12px' }}>反馈面试结果</Button>}
          </Col>
        </Row>
      </div>
      <div style={{ width: '100%', marginTop: '60px' }}>
        {userInfo ? <Outlet /> : <Navigate to="/login" replace />}
      </div>
      <div >
        <Drawer
          placement="left"
          closable={false}
          onClose={onClose}
          open={open}
          key="left"
          width="50%"
          styles={{ body: { width: '100%', padding: '0px' } }}
        >
          <div className={styles.drawer}>
            <div >
              <Row style={{ justifyContent: 'center', alignItems: 'center', marginTop: '20px' }}>
                {!userInfo?.sysUserHead ? (
                  <Avatar icon={<UserOutlined />} size={95} />
                ) : (
                  <Avatar src={userInfo.sysUserHead} size={95} />
                )}
              </Row>
              <Row style={{ justifyContent: 'center', alignItems: 'center', marginTop: '10px', fontSize: '20px', color: '#666666' }}>
                <div >{userInfo?.staffName}</div>
              </Row>
            </div >
            <div className={styles.Menu}>
              <ConfigProvider
                theme={{
                  components: {
                    Menu: {
                      itemHeight: 60
                    }
                  }
                }}
              >
                <Menu
                  mode="inline"
                  defaultSelectedKeys={['231']}
                  onClick={(e) => handleMenuClick(e)}
                  items={filteredItems}
                  style={{ fontSize: '20px' }}
                />
              </ConfigProvider>
            </div>

          </div>
        </Drawer>
      </div>
    </div>
  )
}

export default BasicLayout;